<?php

namespace app\admin\controller\finance;

use app\admin\model\course\ClassesConfig;
use app\admin\model\course\OrderGoods;
use app\admin\model\course\OrderLog;
use app\common\controller\Backend;
use app\common\model\User;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\course\Order
     */
    protected $model = null;
    protected $noNeedRight = [];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\course\Order;
        $statusList = $this->model->getStatusList();
        $this->view->assign("statusList", $statusList);
        $this->assignconfig("statusList", $statusList);

        $typeList = $this->model->getTypeList();
        $this->view->assign("typeList", $typeList);
        $this->assignconfig("typeList", $typeList);

        $schoolModel = new \app\admin\model\user\School();
        $schoolGroup = $schoolModel->getAllSchool();
        $this->assignconfig("schoolGroup",$schoolGroup);
    }





    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($otherWhere,$where, $sort, $order, $offset, $limit) = $this->buildparams();
            $myWhere = [];
            if(isset($otherWhere['status'])){
                switch ($otherWhere['status']){
                    case 21: //未排课
//                        $myWhere["sign_up_start_time"] = [">",time()];
                        $ids = OrderGoods::where("teacher_id",0)->column("order_id");
                        $myWhere['order.id'] = ["in", $ids];
                        break;

                    default:
                        $myWhere["order.status"] = $otherWhere['status'];
                        break;
                }
            }
            if(isset($otherWhere['type'])){
                $myWhere["order.type"] = $otherWhere['type'];

            }

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where($myWhere)
                ->order($sort, $order)
                ->paginate($limit);


            foreach ($list as $row) {
                $row->status_text = $this->model->getStatusText($row->status);

                $orderGoods = \app\admin\model\course\OrderGoods::with(["teacher"=>function($query){
                    $query->withField("nickname");
                }])->where("order_id",$row["id"])->select();
//                dump($orderGoods);exit;

                foreach ($orderGoods as $key => &$value){
                    if(mb_strlen($value["course_name"]) >= 12){
                        $value["course_name"] = mb_substr($value["course_name"], 0, 12) . "...";
                    }
                    $row["order_goods"] = $orderGoods;
                }
                $row->getRelation('user')->visible(['nickname']);
                $row = $this->model->dealOrderInfo($row);
            }

            //总金额条件
            $moneyWhere = $myWhere; //将myWhere 传给当前的 防止调整后修改其他的条件
            if(!isset($myWhere['order.type'])){
                $moneyWhere['order.type'] = ["<>",$this->model::TYPE_RESTORE];
            }else{
                if($myWhere['order.type'] == $this->model::TYPE_RESTORE){
                    $moneyWhere['order.type'] = -1111; //不统计
                }else{
                    $moneyWhere['order.type'] = $myWhere['order.type'];
                }
            }

            //订单金额
            $money = $this->model
                ->with(['user'])
                ->where($where)
                ->where($moneyWhere)
                ->sum("order.money");
            //手动录单
            $admin_order = $this->model
                ->with(['user'])
                ->where($where)
                ->where(["order.type"=>$this->model::TYPE_ADMIN])
                ->count();

            //退款单
            $refund_order = $this->model
                ->with(['user'])
                ->where($where)
                ->where(["order.status"=>$this->model::STATUS_REFUND])
                ->count();
            //退款单
            $refund_money = $this->model
                ->with(['user'])
                ->where($where)
                ->where(["order.status"=>$this->model::STATUS_REFUND])
                ->sum("order.money");

            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ["total" => $list->total(),'money' => $money, 'admin_order' => $admin_order,'refund_order'=>$refund_order,'refund_money'=>$refund_money]);
            return json($result);
        }
        return $this->view->fetch();
    }


    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);

        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $otherWhere = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if(isset($filter["status"])){
            $otherWhere["status"] = $filter['status'];
            unset($filter['status']);
        }
        if(isset($filter["type"])){
            $otherWhere["type"] = $filter['type'];
            unset($filter['type']);
        }
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$otherWhere,$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }
}
